#include "tcp.h"

void Argment(int argc, char *argv[]){
	if(argc < 3){
		exit(EXIT_FAILURE);
	}
	
}

int SocketInit(char *argv[], bool server){
	int fd;
	Addr_in addr;
	func_t func = server?bind:connect;
	/*创建套接字*/
	if( (fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
		ErrExit("socket");
	bzero(&addr,sizeof(addr) );
	
	/*设置地址和ip端口号*/
	addr.sin_family = AF_INET;
	addr.sin_port = htons( atoi(argv[2]) );
	if( inet_aton(argv[1], &addr.sin_addr)  == 0 ){
		fprintf(stderr, "Invalid address\n");
		exit(EXIT_FAILURE);
	}

	/*发起连接请求或绑定地址*/
	if( func(fd, (Addr *)&addr, sizeof(addr) ) )
		ErrExit("connect");

	if(server){

		/*地址快速重用*/
		int b_reuse = 1;
		if( (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &b_reuse, sizeof(int)) )< 0)
			ErrExit("setsockopt");

		/*监听模式*/
		if( listen(fd, BACKLOG) )
			ErrExit("listen");


	}
	return fd;
}
